package com.atguigu.yygh.order.controller;


import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.order.service.PaymentInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 支付信息表 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2024-04-16
 */
@Api(tags = "微信支付")
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    //下单 生成二维码
    @ApiOperation(value = "生成微信支付二维码")
    @GetMapping("/createNative/{orderId}")
    public R createNaive(
            @PathVariable("orderId") Long orderId
    ){
        Map map = weixinService.createNative(orderId);
        return R.ok().data(map);
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public R queryPayStatus(
            @PathVariable("orderId") Long orderId
    ){
        //调用查询接口
        Map<String,String> resultMap = weixinService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.name());
        if(resultMap == null){
            return R.error().message("支付失败");
        }
        //2.如果微信支付状态接口返回成功，更新订单状态
        if("SUCCESS".equals(resultMap.get("trade_state"))){//成功
            //更改订单状态，处理支付结果
            String outTradeNo = resultMap.get("out_trade_no");
            paymentInfoService.paySuccess(outTradeNo, PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            //TODO 调用医院接口，通知医院订单支付完成了

            return  R.ok().message("支付成功");
        }
        return R.ok().message("支付中");

    }


}

